"""
本地市场分析工具
提供当LLM不可用时的降级分析功能
"""
from typing import Dict, Any
import pandas as pd
import numpy as np
from loguru import logger

def local_analyze_market(market_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    本地市场分析
    
    参数:
        market_data: 市场数据字典
        
    返回:
        市场分析结果，包含:
        - market_trend: 市场趋势
        - sector_rotation: 行业轮动
        - economic_indicators: 经济指标
        - risk_assessment: 风险评估
    """
    logger.info("执行本地市场分析")
    
    try:
        # 从市场数据中提取指数数据
        indices = market_data.get("indices", {})
        sh_index = pd.DataFrame(indices.get("sh_index", {}))
        sz_index = pd.DataFrame(indices.get("sz_index", {}))
        hs300 = pd.DataFrame(indices.get("hs300", {}))
        
        # 简单趋势分析
        market_trend = "盘整"
        if not sh_index.empty and not sz_index.empty:
            sh_close = sh_index["close"].astype(float)
            sz_close = sz_index["close"].astype(float)
            
            # 计算20日移动平均
            sh_ma20 = sh_close.rolling(window=20).mean().iloc[-1]
            sz_ma20 = sz_close.rolling(window=20).mean().iloc[-1]
            
            if sh_close.iloc[-1] > sh_ma20 and sz_close.iloc[-1] > sz_ma20:
                market_trend = "上涨"
            elif sh_close.iloc[-1] < sh_ma20 and sz_close.iloc[-1] < sz_ma20:
                market_trend = "下跌"
        
        # 简单行业轮动分析
        stock_list = pd.DataFrame(market_data.get("stock_list", {}))
        sector_rotation = {}
        if not stock_list.empty and "industry" in stock_list.columns:
            top_sectors = stock_list["industry"].value_counts().head(3).to_dict()
            sector_rotation = {"hot_sectors": list(top_sectors.keys())}
        
        return {
            "market_trend": market_trend,
            "sector_rotation": sector_rotation,
            "economic_indicators": {
                "gdp": None,
                "pmi": None,
                "cpi": None
            },
            "risk_assessment": {
                "volatility": None,
                "max_drawdown": None
            },
            "summary": "本地分析结果: 市场趋势 - " + market_trend
        }
        
    except Exception as e:
        logger.error(f"本地市场分析失败: {e}")
        return {
            "market_trend": "unknown",
            "sector_rotation": {},
            "economic_indicators": {},
            "risk_assessment": {},
            "summary": "本地分析失败"
        }